import { Quiz, UserAnswer, MistakeNotebook, Question, MistakeQuestion } from "../../types";

const STORAGE_KEYS = {
  QUIZ_HISTORY: 'quiz_history',
  MISTAKE_NOTEBOOKS: 'mistake_notebooks',
};

export const getHistory = (): Quiz[] => {
  const data = localStorage.getItem(STORAGE_KEYS.QUIZ_HISTORY);
  return data ? JSON.parse(data) : [];
};

export const saveHistory = (history: Quiz[]) => {
  localStorage.setItem(STORAGE_KEYS.QUIZ_HISTORY, JSON.stringify(history));
};

export const saveQuizToHistory = (quiz: Quiz) => {
  const history = getHistory();
  const index = history.findIndex(h => h.id === quiz.id);

  let newHistory;
  if (index >= 0) {
    // Update existing (e.g. adding a result)
    newHistory = [...history];
    newHistory[index] = quiz;
  } else {
    // Add new
    newHistory = [quiz, ...history];
  }

  saveHistory(newHistory);
};

export const deleteQuizFromHistory = (quizId: string) => {
  const history = getHistory();
  const newHistory = history.filter(q => q.id !== quizId);
  saveHistory(newHistory);
}

// Mistake Notebook Functions

export const getMistakeNotebooks = (): MistakeNotebook[] => {
  const data = localStorage.getItem(STORAGE_KEYS.MISTAKE_NOTEBOOKS);
  return data ? JSON.parse(data) : [];
};

export const saveMistakeNotebooks = (notebooks: MistakeNotebook[]) => {
  localStorage.setItem(STORAGE_KEYS.MISTAKE_NOTEBOOKS, JSON.stringify(notebooks));
};

export const createMistakeNotebook = (name: string): MistakeNotebook => {
  const notebooks = getMistakeNotebooks();
  const newNotebook: MistakeNotebook = {
    id: Date.now().toString(),
    name,
    questions: [],
    createdAt: Date.now(),
  };
  saveMistakeNotebooks([...notebooks, newNotebook]);
  return newNotebook;
};

export const addQuestionToNotebook = (notebookId: string, question: Question) => {
  const notebooks = getMistakeNotebooks();
  const notebookIndex = notebooks.findIndex(n => n.id === notebookId);

  if (notebookIndex === -1) return;

  const notebook = notebooks[notebookIndex];
  const existingQuestionIndex = notebook.questions.findIndex(q => q.id === question.id);

  if (existingQuestionIndex >= 0) {
    return;
  }
  const mistakeQuestion: MistakeQuestion = {
    ...question,
    addedAt: Date.now(),
  };
  notebook.questions.push(mistakeQuestion);

  notebooks[notebookIndex] = notebook;
  saveMistakeNotebooks(notebooks);
};

export const updateMistakeNotebookName = (id: string, name: string) => {
  const notebooks = getMistakeNotebooks();
  const index = notebooks.findIndex(n => n.id === id);
  if (index >= 0) {
    notebooks[index].name = name;
    saveMistakeNotebooks(notebooks);
  }
};

export const deleteMistakeNotebook = (id: string) => {
  const notebooks = getMistakeNotebooks();
  const newNotebooks = notebooks.filter(n => n.id !== id);
  saveMistakeNotebooks(newNotebooks);
};

export const removeQuestionFromNotebook = (notebookId: string, questionId: string) => {
  const notebooks = getMistakeNotebooks();
  const index = notebooks.findIndex(n => n.id === notebookId);
  if (index >= 0) {
    notebooks[index].questions = notebooks[index].questions.filter(q => q.id !== questionId);
    saveMistakeNotebooks(notebooks);
  }
};

// Cloud sync functions - calling backend API
// Configuration is handled server-side via environment variables
export const uploadToCloud = async (): Promise<boolean> => {
  const history = getHistory();

  try {
    console.log("Uploading to cloud via API...");
    console.log("Data to upload:", history);

    const response = await fetch('/api/sync/upload', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        data: history,
      }),
    });

    const result = await response.json();

    if (!response.ok || !result.success) {
      throw new Error(result.error || 'Upload failed');
    }

    console.log("Upload success:", result.message);
    return true;
  } catch (error) {
    console.error("Upload error:", error);
    throw error;
  }
};

export const downloadFromCloud = async (): Promise<boolean> => {
  try {
    console.log("Downloading from cloud via API...");

    const response = await fetch('/api/sync/download', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    });

    const result = await response.json();

    if (!response.ok || !result.success) {
      throw new Error(result.error || 'Download failed');
    }

    // Save the downloaded data to local storage
    if (result.data && Array.isArray(result.data)) {
      saveHistory(result.data);
      console.log("Download success, data saved:", result.message);
    } else {
      console.log("Download success, no data returned:", result.message);
    }

    return true;
  } catch (error) {
    console.error("Download error:", error);
    throw error;
  }
};